{% extends "lists/base.html" %}
{% load profile %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% load emarkdown %}

{% block title %}
{{ list.title }}
{% endblock %}


{% block extrahead %}
<link rel="canonical" href="{{ list.get_absolute_url }}" />
  <link rel="stylesheet" type="text/css" href="{% static "js-custom-themes/jquery-ui/theme/jquery-ui.css" %}" />
  <link href="{% static "js-custom-themes/tagit/theme/jquery.tagit.css" %}" rel="stylesheet" type="text/css"/>
{% endblock %}


{% block breadcrumb %}
<li><a href="{% url "home" %}">Home</a></li>
<li><a href="">Lists</a></li>
<li class="current">{{ list.title }}</li>
{% endblock %}

{% block content %}

<span itemscope itemtype="http://schema.org/Article">

<div class="row">
  <div class="large-12 columns">
    <h1><span itemprop="name">{{ list.title }}</span>
      {% if request.user.is_authenticated %}
        <a class="symbol right i-b" id="vote" data-tooltip title="Upvote this list" data-type="list" data-id="{{ list.id }}"><i class="fi-check{% if voted %}box{% endif %}"></i></a>
      {% else %}
        <a class="symbol right disable" id="vote" data-tooltip title="Login to save or upvote this list"><i class="fi-check"></i></a>
        {% endif %}</h1>
    <p>{{ list.description|emarkdown }}</p>
    <p class="byline">
      {% with author=list.owner %}
      by <a href="{% url "user-url" author.username %}"><span itemprop="author" itemscope itemtype="http://schema.org/Person">
              <span itemprop="name">{{ author.username }}</span></span></a> | <span itemprop="datePublished" content="{{ list.pubdate }}">{{ list.pubdate|timesince }}</span> ago | <span class="votes y-bg" data-type="list" data-id="{{ list.id }}"><span class="votes-count"> {{ count }} </span><i class="fi-check{% if voted %}box{% endif %}"></i></span><span itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating" class="views y-bg"><span itemprop="ratingValue">{{ list.views }}</span> <i class="fi-eye"></i></span>{% if author = request.user %} | <a href="{% url "list-edit" list_pk=list.pk %}">edit</a>{% endif %}
      {%endwith%}
    </p>
  </div>
</div>

<div class="row" itemprop="articleBody">
  <div class="large-12 columns{% if list.owner = request.user %} my-def-list{% endif %}">
    {% if list.title == reading_list %}
    {% with links=list.links.all %}
    {% for link in links %}
    <hr />
    <h4><a href="{{ link.get_absolute_url }}"><i class="symbol fi-link"></i> {{ forloop.counter }}.</a> <a href="{{ link.url }}">{{ link.title }}</a>{% if list.owner = request.user %}<span class="del has-tip tip-top" data-tooltip title="Remove link from list"> x </span>{% endif %}</h4>
    <p class="byline">
      <a href="{{ link.get_absolute_url }}">{{ link.get_comment_count }} comments</a> | {{ link.pubdate|timesince }} ago
    </p>
    {% endfor %}
    {% endwith %}
    {% else %}
    <div class="listcontent">
      {{ list.html_content|safe }}
    </div>
    {% endif %}
  </div>
</div>

</span>


{% if request.user.is_authenticated %}
<div id="addmodal" class="reveal-modal" data-reveal>
  <h2>Add this link</h2>
  <span id="form-message" class="label" style="display:none"></span>
  {% crispy form %}
  <a class="close-reveal-modal">&#215;</a>
</div>
{% else %}
<div id="login-modal" class="reveal-modal" data-reveal></div>
{% endif %}
{% endblock %}


{% block last_body %}
{% if request.user.is_authenticated %}
<script type="text/javascript" src="{% static "bower_components/jquery-ui/ui/minified/jquery-ui.min.js" %}" ></script>
<script type="text/javascript" src="{% static "bower_components/tag-it/js/tag-it.min.js" %}" ></script>
<script src="//algorithmia.com/assets/javascripts/algorithmia.js" type="text/javascript"></script>

<script>
  window.csrfToken = '{{ csrf_token }}';
</script>
<script src="{% static "js/votes.js" %}"></script>

<script type="text/javascript">
$(function(){
  $("#id_tags").tagit({
    availableTags: [{{ tags_addlink|safe }}],
    autocomplete: {delay: 0, minLength: 2},
    allowSpaces: true
  });
/*
  $('.listcontent').find('a').each(function(index, item) {
    $item = $(item);
    if($item.text() === 'link') {
      $item.addClass('fi-link');
      $item.text('');
    }
  });*/

  $('.listcontent').find('a').each(function(idx){
    if($(this).hasClass('addthis')) {
      $(this).attr('id', idx)
      $(this).on('click', function() {
        var link = $(this).prev('a');
        var url = link.attr('href')
        var title = link.html();
        $('#id_url').val(url);
        $('#id_title').val(title);
        $('#form-message').hide();
        $('.errorField').hide();
        $('.error').removeClass('error');

        $('#id_tags').val('');
        $('.tagit-choice').each(function() {
          $(this).remove();
        });


        $('#addmodal').attr('data-link', idx);
        $('#addmodal').foundation('reveal', 'open');
        $('#algo, .algo').remove();

        var api_key = "a7c2474b72434761b0e9ff6f9332da3f";
        Algorithmia.query("/vhf/AutoTagURL", api_key, url, function(error, result) {
          $('#suggest').after('<div id="algo"><label>Automatic suggestions : </label></div><div class="right algo"><a href="http://algorithmia.com"><img src="{% static "img/algorithmia.png" %}"></a></div>');
          sug = [];
          for(res in result) {
            sug.push('<a><span class="tag suggest_add" style="display: inline-block" tabindex="-1" data-tag="'+ res +'"><span class="t">'+res+'</span></span></a>');
          }
          $('#algo').append(sug.join(' '));

          $('.suggest_add').on('click', function() {
            var $tag = $(this).attr('data-tag');
            $('#id_tags').tagit("createTag", $tag);
          });
        });
      });
    }
  });


  $('#submit-id-submit').click(function(e) {
    e.preventDefault();
    var form = $('#create-link-form');
    var message = $('#form-message');
    $.ajax({
      type:"POST",
      url: form.attr('action'),
      data: 'id={{ list.pk }}&ajax=1&'+form.serialize(),
      error: function(xhr) {
        result = $.parseJSON(xhr.responseText).result;
        if (result == 'added') {
          $('#'+$('#addmodal').attr('data-link')).remove();
          $('#addmodal').foundation('reveal', 'close');
        } else {
          message.show();
          message.text('Invalid form. Please fill required fields.');
          message.removeClass('success').addClass('alert');
        }
        message.show();
      },
    });
  });

    $('#id_tags').on('change', function() {
      $('#suggest').html('');
      $.ajax({
        type:"GET",
        url: '/tag/related/'+$(this).val(),
        success: function(result) {
          result = $.parseJSON(result);
          for(var i = 0; i < result.length; i++) {
            tag = result[i]
            $('#suggest').append('<li class="tag"><a id="ui-id-'+tag.pk+'" class="suggest_add" tabindex="-1" data-tag="'+tag.tag+'"><span class="c">'+tag.count+'</span><span class="t">'+tag.tag+'</span></a></li>');

            $('.suggest_add').on('click', function() {
              var $tag = $(this).attr('data-tag');
              console.log($tag);
              $('#id_tags').tagit("createTag", $tag);
            });
          }
        }
      });
    });

});
</script>
{% else %}
<script>
$(function () {
  $('#vote, .votes').click(function() {
    $('#login-modal').foundation('reveal', 'open', {
      url: "{% url "user-login-modal" %}"
    });
  });
  $('.listcontent').find('a').each(function(){
    if($(this).hasClass('addthis')) {
      $(this).remove();
    }
  });
});
</script>
{% endif %}
{% endblock last_body %}
